#!/usr/bin/env python
# concurrent server

import signal
import socket, os, sys, traceback
import gpio_control

def signal_chld(signum, frame):
    print "child exited, waitpid"
    result = os.waitpid(-1, os.WNOHANG)
    if result[0]:
        print 'child %d' % result[0]

host = ''       # Bind to all interfaces
port = 8888

signal.signal(signal.SIGCHLD, signal_chld)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)


print 'Server is running on port %d; press Ctrl-C to terminate.' % port
def parse_client_data(data):
    if data == '1':
        print 'led1 on'
        gpio_control.populate_export_file(1)
    elif data == '2':
        print 'led2 on'
        gpio_control.populate_export_file(2)
    else:
        print data

def handle_client(clientsock):
    while True:
        data = clientsock.recv(4096)
        if not data: break
        print data
        parse_client_data(data)
    clientsock.close()


# main function starts
while True:
    try:
        clientsock, clientaddr = s.accept()

        # fok a process for this connection
        pid = os.fork()

        if pid:
            clientsock.close()
            continue
        else:
            s.close()   # close listen socket
            # process this connection
            handle_client(clientsock)
            sys.exit(0)
    except socket.error, e:
        pass
